package middle

import (
	"admin/src/res"
	"admin/src/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

var writeUrlList = []string{
	"/api/user/login",
	"/api/user/register",
}

func CheckToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		for _, val := range writeUrlList {
			if val == c.Request.URL.Path {
				c.Next() //如果是白名单直接放行
				return
			}
		}

		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			res.ErrorMsg(c, "请先登录")
			c.Abort()
			return
		}
		token := strings.TrimPrefix(authHeader, "Bearer")
		if token == "" {
			res.ErrorMsg(c, "无效的Token")
			c.Abort()
			return
		}
		claims, err := utils.ParseToken(token)
		if err != nil {
			res.ErrorMsg(c, "无效的Token")
			c.Abort()
			return
		}
		//校验成功通过
		c.Set("user_id", claims.UserId)
		c.Set("username", claims.UserName)
		c.Next()
	}
}
